
Particle::Particle(int k, int L, Set* sets) {
	this->k = k;
	this->L = L;
	this->sets = sets;
	
	this->x = randomPositionVector();
	this->v = randomVelocityVector();
	pBest = new int[k];
	
	calculateFitness();
	
	updatepBestPosition();
}

Particle::~Particle(){
	delete [] x;
	delete [] pBest;
	delete [] v;
}

void Particle::calculateFitness() {
	Set temp;
	temp.union_(&sets[x[0]]);
	
	for( int i = 1; i < k; ++i )
		temp.intersection(&sets[x[i]]);
	
	fitness = temp.cardinality();
}

int* Particle::randomPositionVector() {
	int index[L];
	for (int i = 0; i < L; ++i) {
		index[i] = i;
	}
	
	for(int i = 0; i < L; ++i) {
		swap(&index[i], &index[rand()%L]);
	}
	
	int *x = new int[k];
	
	for(int i = 0; i < k; ++i) {
		x[i] = index[i];
	}
	
	return x;
}

int* Particle::randomVelocityVector() {
	int *v = new int[k];
	for (int i = 0; i < k; ++i) {
		v[i] = rand()%2;
	}
	return v;
}


void Particle::updatepBestPosition(){
	for (int i = 0; i < k; ++i) {
		pBest[i] = x[i];
	}
	fitness_pBest = fitness;
}

void Particle::isValid(){
	for (int i = 0; i < k; ++i) {
		for (int j = i+1; j < k; ++j) {
			if (x[i] == x[j]) {
				cout << "Particula inconsistente!" << endl;
				exit(-1);
			}
		}
	}
}


